//
//  ModelTool.swift
//  ParkManage
//
//  Created by cf on 2020/9/17.
//  Copyright © 2020 diligrp. All rights reserved.
//

import Foundation

//模型映射为字典协议
protocol ModelMappable: Codable {

}

extension ModelMappable {
    
    func toDic() -> [String: Any] {
        return (ModelTool.modelToJson(model: self) as? [String: Any])!
    }
}

class ModelTool {
    
    class func jsonToModel<T>(json: Any, modelType: T.Type) -> T? where T: Codable {
        
        var jsonDic: Any = json
        //如果传入的是json字符串，需要进行转换
        if type(of: json) == String.self {
            let jsonStr = json as? String
            guard let jsonData = jsonStr?.data(using: String.Encoding.utf8, allowLossyConversion: false) else {
                return nil
            }
            guard let jsonObjct = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {
                return nil
            }
            jsonDic = jsonObjct
        }
        if !JSONSerialization.isValidJSONObject(jsonDic) {
              print("json format error")
              return nil
          }
        let jsonDecoder = JSONDecoder()
        guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDic, options: []) else { return nil}
        guard let model = try? jsonDecoder.decode(modelType, from: jsonData) else {return nil}
        
        return model
    }
    
    class func modelToJson<T>(model: T) -> Any? where T: Codable {
        
        let jsonEncoder = JSONEncoder()
        guard let jsonData = try? jsonEncoder.encode(model) else { return nil}
        guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {return nil}
        
        return json
    }
    
    class func getJSONStringFromDic(dic: [String: Any]) -> String {
        
        if (!JSONSerialization.isValidJSONObject(dic)) {
            print("无法解析出JSONString")
            return ""
        }
        
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dic, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        
        return JSONString! as String
    }
}
